package org.jix.weblog.module.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.jix.weblog.module.admin.model.vo.category.FindCategoryPageListReqVO;
import org.jix.weblog.module.admin.model.vo.category.FindCategoryPageListRspVO;
import org.jix.weblog.module.admin.model.vo.category.AddCategoryReqVO;
import org.jix.weblog.module.admin.model.vo.category.DeleteCategoryVO;
import org.jix.weblog.module.admin.service.AdminCategoryService;
import org.jix.weblog.module.common.domain.dos.ArticleCategoryRelDO;
import org.jix.weblog.module.common.domain.dos.CategoryDO;
import org.jix.weblog.module.common.domain.mapper.ArticleCategoryRelMapper;
import org.jix.weblog.module.common.domain.mapper.CategoryMapper;
import org.jix.weblog.module.common.enums.ResponseCodeEnum;
import org.jix.weblog.module.common.exception.BizException;
import org.jix.weblog.module.common.model.VO.SelectRspVO;
import org.jix.weblog.module.common.utils.PageResponse;
import org.jix.weblog.module.common.utils.Response;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.time.LocalDate;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @version 1.0
 * @Author Jix
 * @Date 2024/7/30 9:55
 * @注释
 */

@Service
@Slf4j
public class AdminCategoryServiceImpl implements AdminCategoryService {

    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private ArticleCategoryRelMapper articleCategoryRelMapper;

    /**
     * 添加分类
     * @param addCategoryReqVO
     * @return
     */
    @Override
    public Response addCategory(AddCategoryReqVO addCategoryReqVO) {
        String categoryName = addCategoryReqVO.getName();
        //判断分类是否存在
        CategoryDO categoryDo = categoryMapper.selectByName(categoryName);
        if (Objects.nonNull(categoryDo)) {
            log.warn("分类名称：{} 该分类已存在", categoryName);
            throw new BizException(ResponseCodeEnum.CATEGORY_NAME_IS_EXISTED);
        }
        //构建DO类
        CategoryDO insertCategoryDO = CategoryDO.builder()
                .name(addCategoryReqVO.getName().trim())
                .build();
        //执行insert
        categoryMapper.insert(insertCategoryDO);
        return Response.success();
    }

    /**
     * 分类分页查询
     * @param findCategoryPageListReqVO
     * @return
     */
    @Override
    public PageResponse findCategoryList(FindCategoryPageListReqVO findCategoryPageListReqVO) {
        //获取当前页以及每页需要展示的数据数量
        Long current = findCategoryPageListReqVO.getCurrent();
        Long size = findCategoryPageListReqVO.getSize();
        //分页对象（查询第几页，每页多少数据）
        Page<CategoryDO> page = new Page<>(current, size);
        //查询条件
        LambdaQueryWrapper<CategoryDO> wrapper = new LambdaQueryWrapper<>();
        String name = findCategoryPageListReqVO.getName();
        LocalDate startDate = findCategoryPageListReqVO.getStartDate();
        LocalDate endDate = findCategoryPageListReqVO.getEndDate();

        wrapper.like(StringUtils.isNotBlank(name), CategoryDO::getName, name.trim()) //like模块查询
                .ge(Objects.nonNull(startDate), CategoryDO::getCreateTime, startDate) //>=startDate
                .le(Objects.nonNull(endDate), CategoryDO::getCreateTime, endDate) //<=endDate
                .orderByDesc(CategoryDO::getCreateTime);//按照创建时间倒叙

        //执行查询
        Page<CategoryDO> categoryDoPage = categoryMapper.selectPage(page, wrapper);
        List<CategoryDO> categoryDOS = categoryDoPage.getRecords();
        //DO=>VO
        List<FindCategoryPageListRspVO> vos = null;
        if (!CollectionUtils.isEmpty(categoryDOS)) {
            vos = categoryDOS.stream()
                    .map(categoryDO -> FindCategoryPageListRspVO.builder()
                            .id(categoryDO.getId())
                            .name(categoryDO.getName())
                            .createTime(categoryDO.getCreateTime())
                            .build())
                    .collect(Collectors.toList());
        }
        return PageResponse.success(categoryDoPage, vos);
    }

    /**
     * 删除分类
     * @param deleteCategoryVO
     * @return
     */
    @Override
    public Response deleteCategory(DeleteCategoryVO deleteCategoryVO) {
        //获取分类id
        Long categoryVOId = deleteCategoryVO.getId();
        // 校验该分类下是否已经有文章，若有，则提示需要先删除分类下所有文章，才能删除
        ArticleCategoryRelDO articleCategoryRelDO = articleCategoryRelMapper.selectOneByCategoryId(categoryVOId);

        if (Objects.nonNull(articleCategoryRelDO)) {
            log.warn("==> 此分类下包含文章，无法删除，categoryId: {}", categoryVOId);
            throw new BizException(ResponseCodeEnum.CATEGORY_CAN_NOT_DELETE);
        }
        //删除分类
        categoryMapper.deleteById(categoryVOId);
        return Response.success();
    }

    /**
     * 获取文章分类列表数据
     * @return
     */
    @Override
    public Response findCategorySelectList() {
        //查询所有分类
        List<CategoryDO> categoryDOS = categoryMapper.selectList(null);
        //DO转VO
        List<SelectRspVO> selectRspVOS = null;
        //分类列表不为空
        if (!CollectionUtils.isEmpty(categoryDOS)) {
            //分类ID为value，分类名称为label展示
            selectRspVOS = categoryDOS.stream()
                    .map(categoryDO -> SelectRspVO.builder()
                            .label(categoryDO.getName())
                            .value(categoryDO.getId())
                            .build())
                    .collect(Collectors.toList());
        }
        return Response.success(selectRspVOS);
    }
}
